For Loop in C++

Posted on December 9, 2023 by Vishesh Namdev
Python C C++ Java
C++ Programming

for loop in C is a control structure that allows you to repeatedly execute a block of code a specified number of times. It consists of three parts: initialization, condition, and iteration. This loop is used when the number of iterations is known in advance.

Syntax of for Loop:

for (initialization; condition; iteration)
    // Code to be executed repeatedly
}

1.Initialization: This is the first part of the for loop and is executed only once at the beginning. It's used to set up or initialize a loop control variable. The initialization can be a declaration of a variable or an assignment.

2.Condition: The condition is a Boolean expression that is checked before each iteration of the loop. If the condition evaluates to true, the loop continues to execute. If it evaluates to false initially, the loop may not execute at all. The loop terminates when the condition becomes false.

3.Iteration: The iteration part is executed at the end of each iteration and is typically used to update the loop control variable. It defines how the loop variable should change between iterations.

The code block enclosed within the curly braces {} is the part where you place the code that you want to be executed repeatedly as long as the condition remains true.

How does a for Loop works?

A for loop in C++ works by repeatedly executing a block of code as long as a specified condition remains true. It follows a structured format, consisting of three main components: initialization, condition, and iteration. Here's how a for loop works step by step:

Step 1: The initialization part is executed first, and it typically initializes a loop control variable. This part is only executed once at the beginning of the loop.

Step 2:After the initialization, the condition part is evaluated. If the condition is true, the loop proceeds to the code block; if it's false, the loop terminates. The condition is checked before each iteration.

Step 3: If the condition is true, the loop enters the code block, and the code inside the block is executed.

Step 4: After the code block is executed, the iteration part is performed. It updates the loop control variable for the next iteration. In the example, i++ increments i by 1.

Step 5: The loop then returns to the condition check. If the condition is still true, the loop repeats steps 3 to 4, executing the code block and iterating the loop control variable. This process continues until the condition becomes false.

Example of for loop:

#include <iostream>Copy Code
using namespace std;

int main() {
    for (int i = 0; i < 5; i++) {
        std::cout << i << " ";
    }

    return 0;
}

In the above example, the loop initializes i to 0, executes the loop body (printing the value of i), increments i after each iteration, and continues as long as i is less than 5. The output will be 0 1 2 3 4.